<template>
  <el-card style="height: 80px;">
    <el-form :inline="true" class="form">
      <el-form-item label="用户名：">
        <el-input placeholder="请输入用户名" v-model="keyWord"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="search" type="primary" :disabled="!keyWord">搜索</el-button>
        <el-button @click="reset" type="primary">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin: 10px 0;">
    <el-button @click="addUser" type="primary">添加用户</el-button>
    <el-button :disabled="!selectIdArr.length" type="primary">批量删除</el-button>
    <el-table @click="deleteSelectUser" @selection-change="selectChange" style="margin: 10px  0;" border
      :data="userArr">
      <el-table-column type="selection" align="center"></el-table-column>
      <el-table-column label="#" align="center" type="index"></el-table-column>
      <el-table-column prop="id" label="ID" align="center"></el-table-column>
      <el-table-column prop="username" show-overflow-tooltip label="用户名字" align="center"></el-table-column>
      <el-table-column prop="name" show-overflow-tooltip label="用户名称" align="center"></el-table-column>
      <el-table-column prop="roleName" show-overflow-tooltip label="用户角色" align="center"></el-table-column>
      <el-table-column prop="createTime" show-overflow-tooltip label="创建时间" align="center"></el-table-column>
      <el-table-column prop="updateTime" show-overflow-tooltip label="更新时间" align="center"></el-table-column>
      <el-table-column label="操作" width="300px" align="center">
        <template #="{ row, $index }">
          <el-button @click="setRole(row)" icon="User" type="primary" size="small">分配角色</el-button>
          <el-button @click="updateUser(row)" icon="Edit" type="primary" size="small">编辑</el-button>
          <el-popconfirm @confirm="deleteUser(row.id)" :title="`你确定要删除${row.username}?`" width="260px">
            <template #reference>
              <el-button icon="Delete" type="primary" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination v-model:currentPage="pageNo" v-model:page-size="pageSize" :page-sizes="[5, 7, 9, 11]"
      :background="true" layout="prev, pager, next, jumper,->,sizes,total" :total="total"
      @current-change="getHasUser(pageNo)" @size-change="handler" />
  </el-card>
  <!-- 新增修改用户 -->
  <el-drawer v-model="drawer">
    <template #header>
      <h4>{{ userParams.id ? '更新用户' : '添加用户' }}</h4>
    </template>
    <template #default>
      <el-form :model="userParams" :rules="rules" ref="formRef">
        <el-form-item label="用户姓名" prop="username">
          <el-input v-model="userParams.username" placeholder="用户姓名"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="name">
          <el-input v-model="userParams.name" placeholder="用户昵称"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
          <el-input v-model="userParams.password" placeholder="用户密码"></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </template>
  </el-drawer>
  <!-- 分配角色 -->
  <el-drawer v-model="drawer1">
    <template #header>
      <h4>分配角色(职位)</h4>
    </template>
    <template #default>
      <el-form>
        <el-form-item label="用户姓名">
          <el-input v-model="userParams.username" placeholder="用户姓名" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="角色列表">
          <el-checkbox @change="handleCheckAllChange" v-model="checkAll"
            :indeterminate="isIndeterminate">全选</el-checkbox>
          <el-checkbox-group v-model="userRole" @change="handleCheckedCitiesChange">
            <el-checkbox v-for="role in allRole" :key="role.id" :label="role" :value="role">
              {{ role.roleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="drawer1 = false">取消</el-button>
        <el-button type="primary" @click="confirmClick">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
import { reqUserInfo, reqAddOrUpdateUser, reqAllRole, reqSetUserRole, reqRemoveUser, reqSelectUser } from '@/api/acl/user';
import type { UserResponseData, Records, User, AllRoleResponseData, AllRole, SetRoleData } from '@/api/acl/user/type';
import { ElMessage } from 'element-plus';
import useLayoutSettingStore from '@/store/modules/setting';

// 默认页码
let pageNo = ref<number>(1)
// 一页展示几条数据
let pageSize = ref<number>(5)
// 用户的总个数
let total = ref<number>(0)
// 存储用户全部数据
let userArr = ref<Records>([])
// 定义数据控制抽屉显示隐藏
let drawer = ref<boolean>(false)
// 控制分配角色显示隐藏
let drawer1 = ref<boolean>(false)
// 全选复选框
let checkAll = ref<boolean>(false)
// 设置复选框不确定样式
let isIndeterminate = ref<boolean>(true)
// 存储全部职位数据
let allRole = ref<AllRole>([])
// 当前用户已有的数据
let userRole = ref<AllRole>([])
// 收集用户信息
let userParams = reactive<User>({
  username: '',
  name: '',
  password: ''
})
// 获取form组件实例
const formRef = ref<any>()
// 存储批量删除用户
let selectIdArr = ref<User[]>([])
// 收集用户输入关键字
let keyWord = ref<string>('')
// 获取模板setting仓库
let settingStore = useLayoutSettingStore()

onMounted(() => {
  getHasUser()
})

// 获取全部已有的用户信息
const getHasUser = async (pager = 1) => {
  pageNo.value = pager
  let result: UserResponseData = await reqUserInfo(pageNo.value, pageSize.value, keyWord.value)
  if (result.code == 200) {
    total.value = result.data.total
    userArr.value = result.data.records
  }
}

// 下拉菜单
const handler = () => {
  getHasUser()
}

// 添加用户
const addUser = () => {
  drawer.value = true
  // 清空数据
  Object.assign(userParams, {
    id: '',
    username: '',
    name: '',
    password: ''
  })
  // 清除上一次的提示信息
  nextTick(() => {
    formRef.value.clearValidate('username')
    formRef.value.clearValidate('name')
    formRef.value.clearValidate('password')
  })
}

// 更新用户
const updateUser = (row: User) => {
  drawer.value = true
  // 存储收集已有账号信息
  Object.assign(userParams, row)
  // 清除上一次的提示信息
  nextTick(() => {
    formRef.value.clearValidate('username')
    formRef.value.clearValidate('name')
  })
}

// 保存按钮
const save = async () => {
  // 点击保存务必保证表单全部符合校验条件 再去发请求
  await formRef.value.validate()
  // 添加新的用户、更新用户
  let result: any = await reqAddOrUpdateUser((userParams as User))
  if (result.code == 200) {
    drawer.value = false
    ElMessage({
      type: 'success',
      message: userParams.id ? '更新成功' : '添加成功'
    })
    // getHasUser(userParams.id ? pageNo.value : 1)
    // 浏览器自动刷新一次
    window.location.reload()
  } else {
    drawer.value = false
    ElMessage({
      type: 'error',
      message: userParams.id ? '更新失败' : '添加失败'
    })
  }
}

// 取消按钮 
const cancel = () => {
  drawer.value = false
}

// 校验用户名字
const validatorUsername = (rule: any, value: any, callBack: any) => {
  // 用户名字长度至少五位
  if (value.trim().length >= 5) {
    callBack()
  } else {
    callBack(new Error('用户名字至少五位'))
  }
}
// 校验用户昵称
const validatorName = (rule: any, value: any, callBack: any) => {
  // 用户名字长度至少五位
  if (value.trim().length >= 5) {
    callBack()
  } else {
    callBack(new Error('用户昵称至少五位'))
  }
}
// 校验用户密码
const validatorPassword = (rule: any, value: any, callBack: any) => {
  // 用户名字长度至少五位
  if (value.trim().length >= 6) {
    callBack()
  } else {
    callBack(new Error('用户密码至少六位'))
  }
}

// 表单校验规则
const rules = {
  // 用户名字
  username: [{ required: true, trigger: 'blur', validator: validatorUsername }],
  // 用户昵称
  name: [{ required: true, trigger: 'blur', validator: validatorName }],
  // 用户密码
  password: [{ required: true, trigger: 'blur', validator: validatorPassword }],
}

// 分配角色
const setRole = async (row: User) => {
  Object.assign(userParams, row)
  // 获取全部职位,当前账号拥有的职位
  let result: AllRoleResponseData = await reqAllRole(userParams.id)
  if (result.code == 200) {
    // 存储全部职位
    allRole.value = result.data.allRolesList
    // 存储当前用户已有的职位
    userRole.value = result.data.assignRoles
    drawer1.value = true
  }
}


// 全选复选框change事件
const handleCheckAllChange = (val: boolean) => {
  userRole.value = val ? allRole.value : []
  isIndeterminate.value = false
}
// 底部复选框change事件
const handleCheckedCitiesChange = (value: string[]) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === allRole.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < allRole.value.length
}

// 确定按钮(分配角色)
const confirmClick = async () => {
  // 收集参数
  let data: SetRoleData = {
    userId: userParams.id,
    roleIdList: userRole.value.map((item: any) => item.id)
  }

  let result: any = await reqSetUserRole(data)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '分配角色成功'
    })
    drawer1.value = false
    getHasUser(pageNo.value)
  } else {
    ElMessage({
      type: 'error',
      message: '分配角色失败'
    })
  }
}

// 删除某一个用户
const deleteUser = async (userId: number) => {
  let result: any = await reqRemoveUser(userId)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    getHasUser(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败'
    })
  }
}

// table复选框勾选
const selectChange = (value: any) => {
  selectIdArr.value = value
}

// 批量删除
const deleteSelectUser = async () => {
  let idList: any = selectIdArr.value.map((item: any) => item.id)

  let result: any = await reqSelectUser(idList)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    getHasUser(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败'
    })
  }
}

// 搜索按钮
const search = () => {
  getHasUser()
  keyWord.value = ''
}

// 重置按钮
const reset = () => {
  settingStore.refresh = !settingStore.refresh
}
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>